import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:get/get.dart';

import 'url_base.dart';

class BaseProvider extends GetConnect {
  late String appId;
  late String appkey;
  String nonceStr = "ssBbeJEy1aQlZhE4KqUQ";
  DateTime now = DateTime.now();

  BaseProvider() {
    appId = "meiyunAdmin";
    appkey = "meiyunAdmin20210603UjnrUaGRZYAvL44ajuDqmR56IIIC";
  }

  @override
  void onInit() {
    super.onInit();
    httpClient.baseUrl = UrlBase.getBaseUrl();

    num timestamp = now.millisecondsSinceEpoch;
    String value =
        "appId=$appId&nonceStr=$nonceStr&timestamp=$timestamp$appkey";

    String sign = generateMd5(value).toUpperCase();
    // 请求拦截
    httpClient.addRequestModifier<void>((request) {
      request.headers['appId'] = appId;
      request.headers['nonceStr'] = nonceStr;
      request.headers['timestamp'] = timestamp.toString();
      request.headers['sign'] = sign;
      return request;
    });

    // 响应拦截
    httpClient.addResponseModifier((request, response) {
      return response;
    });
  }

  String generateMd5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString();
  }
}
